//
//  YZDieOutVC.m
//  VET
//
//  Created by 刘文靖 on 2018/7/21.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZDieOutVC.h"
#import "MJRefresh.h"
#import "YZDieOutCell.h"
#import "YZActionSheet.h"
#import "YZRouter+AutoVC.h"
#import "PopoverView.h"
#import "YZDieOutModel.h"
#import "MJExtension.h"
#import "YZWorkbenchAPI.h"
#import "YZDieOutTrackVC.h"
#import "YZPopupController.h"
#import "YZPopupCustomView.h"
#import "YZPigDeathDetailVC.h"
#import "YZPigGroupDeathDetailVC.h"
#import "YZSwineHeaderView.h"
#import "YZDieoutSearchResultController.h"
@interface YZDieOutVC ()<UITableViewDelegate,UITableViewDataSource,YZDieOutCellDelegate,YZActionSheetDelegate,UIGestureRecognizerDelegate,YZSwineHeaderViewDelegate>
@property (strong, nonatomic) NSMutableArray <YZDieOutModel *>*dataSource;
@property (strong, nonatomic) UIView *emptyView;
@property (strong, nonatomic) YZSwineHeaderView *navigationView;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) YZDieOutModel *selectedModel;
@property (strong, nonatomic) NSIndexPath *selectedIndexPath;
@property (assign, nonatomic) NSInteger currentPage;

@end
#define kPagePerCount 10
#define knaviBarHeight kStatusBarHeight + 48
@implementation YZDieOutVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColorWithHex(0xf5f5f5);
    [self setupNavigationBar];
    [self setupRefresh];
    
    // 编辑新增猪群后更新
    @weakify(self)
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:kDieoutRefreshNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        
        // 获取新数据
        @strongify(self)
        [self.tableView.mj_header beginRefreshing];
        
    }];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    // 支持右滑返回
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)setupNavigationBar{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    YZSwineHeaderView *headerView = [[YZSwineHeaderView alloc] initWithType:YZSwineHeaderViewDieout];
    headerView.delegate = self;
    [self.view addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.height.mas_equalTo(144 + kStatusBarHeight);
    }];
    self.navigationView = headerView;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.tableFooterView = [UIView new];
}

- (void)setupRefresh {
    
    // 设置刷新控件
    @weakify(self)
    
    // header
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        [self loadNewData];
    }];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    // 隐藏状态
    header.stateLabel.hidden = YES;
    self.tableView.mj_header = header;
    // 请求数据
    [self.tableView.mj_header beginRefreshing];
    
    // footer
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        [self loadMoreData];
    }];
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
}

- (void)loadNewData{
    @weakify(self)
    [[YZDieOutModelAPI requestDieoutList:0 number:nil] subscribeNext:^(NSDictionary *dict) {
        @strongify(self)
        self.currentPage = 1;
        self.dataSource = [YZDieOutModel mj_objectArrayWithKeyValuesArray:dict[@"list"]];
        if (self.dataSource.count < kPagePerCount) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer resetNoMoreData];
            self.tableView.mj_footer.hidden = NO;
        }
        [self.tableView.mj_header endRefreshing];
        [self refreshTableView];
    } error:^(NSError * _Nullable error) {
        @strongify(self)
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData{
    @weakify(self)
    [[YZDieOutModelAPI requestDieoutList:self.currentPage number:nil] subscribeNext:^(NSDictionary *dict) {
        @strongify(self)
        ++self.currentPage;
        [self.tableView.mj_footer endRefreshing];
        [self.dataSource addObjectsFromArray:[YZDieOutModel mj_objectArrayWithKeyValuesArray:dict[@"list"]]];
        if (self.dataSource.count % kPagePerCount) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer resetNoMoreData];
        }
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self)
        [self.tableView.mj_footer endRefreshing];
    }];
    
}

- (void)refreshTableView{
    if (self.dataSource.count) {
        self.emptyView.hidden = YES;
    }else{
        [self showEmptyView];
    }
    [self.tableView reloadData];
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, knaviBarHeight, kScreenWidth,kScreenHeight - knaviBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundView.backgroundColor = [UIColor clearColor];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.rowHeight = 163;
        [_tableView registerClass:[YZDieOutCell class] forCellReuseIdentifier:@"YZDieOutCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        UIView * clearview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 96)];
        clearview.backgroundColor = [UIColor clearColor];
        _tableView.tableHeaderView = clearview;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (void)showEmptyView{
    self.tableView.mj_footer.hidden = YES;
    if (self.emptyView) {
        self.emptyView.hidden = NO;
    }else{
        self.emptyView = [[UIView alloc] init];
        self.emptyView.layer.contents = (__bridge id)[UIImage imageNamed:@"card_background"].CGImage;
        
        UILabel *emptyLabel = [[UILabel alloc] init];
        emptyLabel.text = @"还没有死淘管理卡";
        emptyLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        emptyLabel.textColor = kColorWithHex(0x9b9b9b);
        [self.emptyView addSubview:emptyLabel];
        [emptyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.offset(0);
            make.height.mas_equalTo(20);
            make.top.offset(59);
        }];
        
        UIButton *pigaddBtn = [[UIButton alloc] init];
        [pigaddBtn setTitle:@"猪只死淘" forState:UIControlStateNormal];
        [pigaddBtn setTitleColor:kColorWithHex(0x32BE60) forState:UIControlStateNormal];
        pigaddBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        [pigaddBtn setImage:[UIImage imageNamed:@"empty_add"] forState:UIControlStateNormal];
        pigaddBtn.layer.borderWidth = 1;
        pigaddBtn.layer.borderColor = kColorWithHex(0x32BE60).CGColor;
        pigaddBtn.layer.cornerRadius = 4;
        [self.emptyView addSubview:pigaddBtn];
        [pigaddBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(110, 40));
            make.left.offset(57);
            make.top.mas_equalTo(emptyLabel.mas_bottom).offset(21);
        }];
        
        UIButton *herdaddBtn = [[UIButton alloc] init];
        [herdaddBtn setTitle:@"猪群死淘" forState:UIControlStateNormal];
        [herdaddBtn setTitleColor:kColorWithHex(0x32BE60) forState:UIControlStateNormal];
        herdaddBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        [herdaddBtn setImage:[UIImage imageNamed:@"empty_add"] forState:UIControlStateNormal];
        herdaddBtn.layer.borderWidth = 1;
        herdaddBtn.layer.borderColor = kColorWithHex(0x32BE60).CGColor;
        herdaddBtn.layer.cornerRadius = 4;
        [self.emptyView addSubview:herdaddBtn];
        [herdaddBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(110, 40));
            make.left.mas_equalTo(pigaddBtn.mas_right).offset(12);
            make.top.mas_equalTo(emptyLabel.mas_bottom).offset(21);
        }];
        
        [self.tableView addSubview:self.emptyView];
        [self.emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(11);
            make.right.offset(-11);
            make.top.offset(108);
            make.size.mas_equalTo(CGSizeMake(kScreenWidth - 22, 182));
        }];
        [[pigaddBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [[YZRouter sharedInstance] yz_atuoPush:@"mutableDeadSignSwine"];
        }];
        
        [[herdaddBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [[YZRouter sharedInstance] yz_atuoPush:@"mutableDeadSignSwinery"];
        }];
    }
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YZDieOutCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YZDieOutCell"];
    cell.model = self.dataSource[indexPath.row];
    cell.delegate = self;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YZDieOutModel *model = self.dataSource[indexPath.row];
    if ([model.type isEqualToString:@"swine"]) {
        YZPigDeathDetailVC *pigDeathDetailVC = [YZPigDeathDetailVC new];
        pigDeathDetailVC.model = model;
        [[YZRouter sharedInstance] pushVC:pigDeathDetailVC];
    }else
    {
        YZPigGroupDeathDetailVC *pigGroupDeathDetailVC = [YZPigGroupDeathDetailVC new];
        pigGroupDeathDetailVC.model = model;
        [[YZRouter sharedInstance] pushVC:pigGroupDeathDetailVC];
    }
}

#pragma mark - YZSwineArchieveCellDelegate
- (void)cellDidClickManage:(YZDieOutCell *)cell{
    YZActionSheet *sheet = [[YZActionSheet alloc] initWithTitle:nil sheetTitles:@[@"死淘跟踪",@"删除"] cancleBtnTitle:@"取消" sheetStyle:YZActionSheetDefault delegate:self];
    sheet.sheetHeight = 55;
    sheet.subtitleFont = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    sheet.subtitleColor = kColorWithHex(0x393939);
    sheet.lineColor = kColorWithHex(0xD9D9D9);
    sheet.cancleHeight = 55;
    sheet.bottomMarginHeight = 15;
    sheet.cancelTitleFont = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    sheet.cancelTitleColor = kColorWithHex(0x393939);
    self.selectedModel = cell.model;
    self.selectedIndexPath = [self.tableView indexPathForCell:cell];
    [sheet show];
}

#pragma mark - YZActionSheetDelegate
/**
 点击actionSheet代理方法
 
 @param actionSheet actionSheet
 @param buttonIndex index
 */
- (void)actionSheet:(YZActionSheet *)actionSheet clickButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0://死淘跟踪
        {
            YZDieOutTrackVC *trackVC = [[YZDieOutTrackVC alloc] init];
            trackVC.trackId = self.selectedModel.dieOutId;
            [[YZRouter sharedInstance] pushVC:trackVC];
        }
            ;
            break;
            
        case 1://删除
        {
            YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
            @weakify(self)
            [customView setupUIWithTitle:nil message:@"确定删除当前死淘记录？删除后不可恢复已记录信息。" confirmTitle:@"删除" cancelTitle:@"取消" confirmHandler:^{
                @strongify(self)
                // 删除猪只
                NSString *dieOutId = [@(self.selectedModel.dieOutId) stringValue];
                @weakify(self)
                [[YZWorkbenchAPI deleteDeadSignAPIWithParams:dieOutId] subscribeNext:^(id  _Nullable x) {
                    @strongify(self)
                    [self.YZ_popupController dismiss];
                    [self.dataSource removeObject:self.selectedModel];
                    [self.tableView deleteRowsAtIndexPaths:@[self.selectedIndexPath] withRowAnimation:UITableViewRowAnimationLeft];
                    if (self.dataSource.count == 0) {
                        [self showEmptyView];
                    }
                } error:^(NSError * _Nullable error) {
                    @strongify(self)
                    [self.YZ_popupController dismiss];
                }];
                
            } cancelHandler:^{
                @strongify(self)
                [self.YZ_popupController dismiss];
            }];
            [self.YZ_popupController presentContentView:customView];
        }
            break;
    }
}
- (void)actionSheetCancle:(YZActionSheet *)actionSheet{}


#pragma mark - YZSwineHeaderViewDelegate
- (void)backButtonClicked{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)menuButtonClick:(UIButton *)sender{
    PopoverView *popoverView = [PopoverView popoverView];
    popoverView.showShade = YES; // 显示阴影背景
    [popoverView showToView:sender withActions:[self POPActions]];
}

- (void)searchButtonClicked{
    YZDieoutSearchResultController *searchVC = [[YZDieoutSearchResultController alloc] init];
    [self presentViewController:searchVC animated:NO completion:nil];
}
#pragma mark - PopoverVie

- (NSArray<PopoverAction *> *)POPActions {
    //猪只死淘 action
    PopoverAction *pigtAction = [PopoverAction actionWithTitle:@"猪只死淘" handler:^(PopoverAction *action) {
        
        [[YZRouter sharedInstance] yz_atuoPush:@"mutableDeadSignSwine"];
        
    }];
    
    // 猪群死淘 action
    PopoverAction *swineryAction = [PopoverAction actionWithTitle:@"猪群死淘" handler:^(PopoverAction *action) {
        
        [[YZRouter sharedInstance] yz_atuoPush:@"mutableDeadSignSwinery"];
        
    }];
    
    return @[pigtAction, swineryAction];
}

#pragma scrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.dataSource.count == 0) return;
    CGFloat topImageView2y = 96;
    float contentOffsety = scrollView.contentOffset.y;
    self.navigationView.searchBtn.alpha = (topImageView2y - contentOffsety * 2)/topImageView2y;
    if (contentOffsety > 0) {
        [self.navigationView.searchBtn setTop:(knaviBarHeight + 20 - contentOffsety)];
    }
    if (self.navigationView.searchBtn.alpha == 1) {
        [self.view bringSubviewToFront:self.navigationView];
    }else{
        [self.view bringSubviewToFront:self.tableView];
    }
    self.navigationView.rightSearchBtn.alpha = 1-self.navigationView.searchBtn.alpha;
}

@end
